/* Copyright (c) 2008 Charles Rich and Worcester Polytechnic Institute.
 * All Rights Reserved.  Use is subject to license terms.  See the file
 * "license.terms" for information on usage and redistribution of this
 * file and for a DISCLAIMER OF ALL WARRANTIES.
 */
package edu.wpi.cetask;

import org.w3c.dom.Node;

import javax.script.ScriptException;

public class Script extends Description implements Description.Taskable {
   
   private final TaskClass task;
   
   public TaskClass getTask () { return task; } // Taskable
   
   public Boolean isApplicable (Task goal) {
      return goal.evalCondition(xpath("./@applicable"), this+" applicable");
   }
      
   Script (Node node, TaskEngine engine, TaskClass task) {
      super(node, engine);
      if ( task == null ) {
         String qname = xpath("./@task");
         if ( qname.length() > 0 ) task = resolveTaskClass(qname);
      }
      this.task = task;
   }
     
   public String getModel () {
      return Utils.emptyNull(xpath("./@model"));
   }
   
   public String getPlatform () {
      return Utils.emptyNull(xpath("./@platform"));
   }
   
   public String getDeviceType () {
      return Utils.emptyNull(xpath("./@deviceType"));
   }
   
   public boolean isInit () {
      return Boolean.parseBoolean(xpath("./@init"));
   }
   
   public String getText () { return xpath("."); }
   
   public Object eval (Task task) {
      // assuming that $platform and $deviceType already in task.bindings
      try { return engine.eval(getText(), task.bindings, task+" script"); } 
      catch (ScriptException e) { throw new RuntimeException(e); }
   }
}
